﻿using DTcms.Core.Common.Emum;
using DTcms.Core.Common.Helper;
using DTcms.Core.IServices;
using DTcms.Core.IServices.Alipay;
using DTcms.Core.Model.Alipay;
using DTcms.Core.Model.Models;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web;

namespace DTcms.Core.API.Controllers
{
    [Area("api")]
    [Route("api/[controller]")]
    [ApiController]
    public class AlipayController : ControllerBase
    {
        private readonly IAlipayExecute _alipayExecute;
        private readonly ISitePaymentService _sitePaymentService;
        private readonly IMemberRechargeService _memberRechargeService;
        public AlipayController(IAlipayExecute alipayExecute, ISitePaymentService sitePaymentService,
            IMemberRechargeService memberRechargeService)
        {
            _alipayExecute = alipayExecute;
            _sitePaymentService = sitePaymentService;
            _memberRechargeService = memberRechargeService;
        }

        /// <summary>
        /// 支付宝统一下单
        /// 示例：/api/alipay
        /// </summary>
        [HttpPost]
        public async Task<IActionResult> Pay(AlipayTradeDto modelDto)
        {
            //判断充值订单
            if (modelDto.OutTradeNo.StartsWith("RN"))
            {
                //充值订单状态
                var model = await _memberRechargeService.QueryAsync<MemberRecharge>(x => x.RechargeNo == modelDto.OutTradeNo, WriteRoRead.Write);
                if (model == null)
                {
                    throw new ResponseException("充值订单号有误，请重试");
                }
                if (model.Status == 1)
                {
                    throw new ResponseException("订单已支付，请勿重复付款");
                }
                if (model.Amount <= 0)
                {
                    throw new ResponseException("支付金额必须大于零");
                }
                //赋值支付方式及总金额
                modelDto.PaymentId = model.PaymentId;
                modelDto.Total = model.Amount;
            }
            //防止用户URL编码，URL解码
            modelDto.ReturnUri = HttpUtility.UrlDecode(modelDto.ReturnUri);
            //判断支付接口类型
            var pay = await _sitePaymentService.QueryAsync<SitePayment>(x => x.Id == modelDto.PaymentId);
            if (pay == null)
            {
                throw new ResponseException("支付方式有误，请重试");
            }
            else if (pay.Type == "pc")
            {
                return Ok(await _alipayExecute.PcPayAsync(modelDto));
            }
            throw new ResponseException("支付方式有误，请重试");
        }

    }
}
